package com.jt.service;


import com.alibaba.dubbo.config.annotation.Service;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jt.mapper.UserMapper;
import com.jt.pojo.User;
import com.jt.util.ObjectMapperUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;
import redis.clients.jedis.JedisCluster;

import java.util.UUID;


@Service(timeout = 3000)
public class DobboUserServiceImpl implements DubboUserService {
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private JedisCluster jedisCluster;


    @Override
    public void saveUser(User user) {
        byte[] bytes = user.getPassword().getBytes();
        //利用Spring工具API进行加密操作
        String md5Pass = DigestUtils.md5DigestAsHex(bytes);
        user.setPassword(md5Pass).setEmail(user.getPhone());
        userMapper.insert(user);
    }



    /**
     * 1.校验用户名和密码是否正确  不存在则直接返回Null
     * 2.如果存在：动态生成密钥  将用户转化为JSON
     * 3.将数据保存刀redis中7天有效
     * 4.返回密钥ticket信息.
     *
     * @param user
     * @return
     *
     * */
    @Override
    public String findUserByUP(User user) {
        String md5Pass = DigestUtils.md5DigestAsHex(user.getPassword().getBytes());
        user.setPassword(md5Pass);
        // 1.根据对象中不为null的属性当作where条件
        QueryWrapper<User> queryWrapper =new QueryWrapper<>(user);
        User userDB = userMapper.selectOne(queryWrapper);

        // 2.判断对象是否有值
        if (userDB == null){
            return null;
        }

        // 3.表示用户名和密码正确，开启单点登录
        String ticket =   //replace -->去掉横线
                UUID.randomUUID().toString().replace("-", "");
        //转化之前将数据进行脱敏处理
        userDB.setPassword("123456");
        String userJSON = ObjectMapperUtil.toJSON(userDB);

        // 4.将数据保存到redis中'
        jedisCluster.setex(ticket,7*24*60*60,userJSON);
        //返回密钥
        return ticket;
    }
}
